package com.paradox.aggregation.provider.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

public class ChatClient {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup workers=new NioEventLoopGroup(1);

        try {
            Bootstrap bootstrap=new Bootstrap();
            bootstrap.group(workers).channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline=ch.pipeline();
                            pipeline.addLast(new StringEncoder());
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new ClientHandler());
                        }
                    });
            ChannelFuture channelFuture=bootstrap.connect("127.0.0.1",9000).sync();
            System.out.println("客户端已启动！");
            Channel channel=channelFuture.channel();
            Scanner scanner=new Scanner(System.in);
            while(scanner.hasNext()){
                channel.writeAndFlush(scanner.nextLine());
            }
        }finally {
            workers.shutdownGracefully();
        }
    }
}
